import 'package:flutter/material.dart';
import '../models/word.dart';
import '../services/database_service.dart';
import 'add_word_screen.dart';
import 'review_screen.dart';
import 'settings_screen.dart';
import 'import_export_screen.dart';
import 'statistics_screen.dart';
import 'quiz_screen.dart';
import 'learning_screen.dart'; // Add this line

class WordListScreen extends StatefulWidget {
  const WordListScreen({super.key});

  @override
  _WordListScreenState createState() => _WordListScreenState();
}

class _WordListScreenState extends State<WordListScreen> {
  final DatabaseService _databaseService = DatabaseService();
  List<Word> _words = [];
  List<Map<String, dynamic>> _categories = [];
  int? _selectedCategoryId;
  Map<String, dynamic> _statistics = {
    'totalWords': 0,
    'masteredWords': 0,
    'needReviewWords': 0,
  };
  int _selectedIndex = 0;
  final PageController _pageController = PageController();

  @override
  void initState() {
    super.initState();
    _loadWords();
    _loadCategories();
    _loadStatistics();
  }

  Future<void> _loadCategories() async {
    final categories = await _databaseService.getCategories();
    setState(() {
      _categories = categories;
    });
  }

  Future<void> _loadWords() async {
    final words = await _databaseService.getWords();
    setState(() {
      if (_selectedCategoryId != null) {
        _words = words.where((w) => w.categoryId == _selectedCategoryId).toList();
      } else {
        _words = words;
      }
    });
  }

  Future<void> _loadStatistics() async {
    final stats = await _databaseService.getStatistics();
    setState(() {
      _statistics = stats;
    });
  }

  Future<void> _showCategoryDialog(Word word) async {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('选择分类'),
        content: SizedBox(
          width: double.maxFinite,
          child: ListView.builder(
            shrinkWrap: true,
            itemCount: _categories.length,
            itemBuilder: (context, index) {
              final category = _categories[index];
              return ListTile(
                title: Text(category['name']),
                leading: CircleAvatar(
                  backgroundColor: Color(int.parse(category['color'].substring(2), radix: 16)),
                ),
                onTap: () async {
                  await _databaseService.updateWordCategory(word.id!, category['id']);
                  Navigator.pop(context);
                  _loadWords();
                },
              );
            },
          ),
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('我的单词本'),
        actions: [
          IconButton(
            icon: const Icon(Icons.refresh),
            onPressed: () async {
              await Navigator.push(
                context,
                MaterialPageRoute(builder: (context) => const ReviewScreen()),
              );
              _loadWords();
              _loadStatistics();
            },
          ),
          IconButton(
            icon: const Icon(Icons.settings),
            onPressed: () async {
              await Navigator.push(
                context,
                MaterialPageRoute(builder: (context) => const SettingsScreen()),
              );
            },
          ),
          PopupMenuButton(
            itemBuilder: (context) => [
              PopupMenuItem(
                child: const Text('导入导出'),
                onTap: () async {
                  await Navigator.push(
                    context,
                    MaterialPageRoute(builder: (context) => const ImportExportScreen()),
                  );
                  _loadWords();
                  _loadStatistics();
                },
              ),
            ],
          ),
        ],
      ),
      body: Column(
        children: [
          SingleChildScrollView(
            scrollDirection: Axis.horizontal,
            padding: const EdgeInsets.symmetric(horizontal: 16),
            child: Row(
              children: [
                FilterChip(
                  label: const Text('全部'),
                  selected: _selectedCategoryId == null,
                  onSelected: (selected) {
                    setState(() {
                      _selectedCategoryId = null;
                    });
                    _loadWords();
                  },
                ),
                ...(_categories.map((category) => Padding(
                  padding: const EdgeInsets.only(left: 8),
                  child: FilterChip(
                    label: Text(category['name']),
                    selected: _selectedCategoryId == category['id'],
                    avatar: CircleAvatar(
                      backgroundColor: Color(int.parse(category['color'].substring(2), radix: 16)),
                      radius: 8,
                    ),
                    onSelected: (selected) {
                      setState(() {
                        _selectedCategoryId = selected ? category['id'] : null;
                      });
                      _loadWords();
                    },
                  ),
                ))).toList(),
              ],
            ),
          ),
          const SizedBox(height: 16),
          Expanded(
            child: PageView(
              controller: _pageController,
              physics: const NeverScrollableScrollPhysics(),
              children: <Widget>[
                LearningScreen(),
                StatisticsScreen(),
                QuizScreen(),
              ],
            ),
          ),
        ],
      ),
      bottomNavigationBar: BottomNavigationBar(
        items: const <BottomNavigationBarItem>[
          BottomNavigationBarItem(
            icon: Icon(Icons.book),
            label: '学习单词',
          ),
          BottomNavigationBarItem(
            icon: Icon(Icons.analytics),
            label: '学习统计',
          ),
          BottomNavigationBarItem(
            icon: Icon(Icons.question_answer),
            label: '单词测试',
          ),
        ],
        currentIndex: _selectedIndex,
        onTap: (index) {
          setState(() {
            _selectedIndex = index;
            _pageController.jumpToPage(index);
          });
        },
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () async {
          await Navigator.push(
            context,
            MaterialPageRoute(builder: (context) => const AddWordScreen()),
          );
          _loadWords();
          _loadStatistics();
        },
        child: const Icon(Icons.add),
      ),
    );
  }

  Widget _buildStatItem(String label, String value) {
    return Column(
      children: [
        Text(
          value,
          style: TextStyle(
            fontSize: 24,
            fontWeight: FontWeight.bold,
            color: Theme.of(context).primaryColor,
          ),
        ),
        Text(
          label,
          style: TextStyle(
            fontSize: 14,
            color: Colors.grey[600],
          ),
        ),
      ],
    );
  }
}
